package com.example.weight.wormHandle.cultivate;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.config.Config;
import com.example.weight.util.WeightActivity;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public class BigBugFirstFeed extends AppCompatActivity {
    final DecimalFormat formater = new DecimalFormat();
    private MiddleWormBox toAddBox;

    private String name,firstAdd_belongTo_id,firstAdd_Text, factory;
    private  int belongTo_id = -1;

    private TextView batch_content, tv_big_out_date, tv_number;
    private Spinner sp_go_where;
    private EditText et_breed_no, et_middle_worm_quality, et_target, et_fact, et_per_box_material;

    String currentSerialId;
    int serialId;

//    private EditText box_weight;

    //第一次加料重量
    private TextView jialiao_weight;
    //备注
    private EditText remark;
    String activeButton = new String();

    private List<String> gowhereList;

    Calendar calendar= Calendar.getInstance(Locale.CHINA);
    @SuppressLint("SimpleDateFormat")
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

    //备选批次等列表
    private List<MiddleWormBox> bigBugBatchGroupNumberFirstAddList;

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_big_bug_first_feed);

        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");
        factory = previousIntent.getStringExtra("factory");
        toAddBox = (MiddleWormBox) previousIntent.getSerializableExtra("toAddBox");
//        Toast.makeText(this, "firstAdd_belongTo_id:"+firstAdd_belongTo_id, Toast.LENGTH_SHORT).show();

        //去向五选一
        gowhereList = new ArrayList<>();
        gowhereList.add("书箱");
        gowhereList.add("书柜");
        gowhereList.add("育种");
        gowhereList.add("项目");
        gowhereList.add("其它");

        currentSerialId = toAddBox.getSerialId();
        serialId = Integer.parseInt(currentSerialId)+1;
        Log.d("sc",currentSerialId);
        Log.d("s",serialId+"");

        TitleBar titleBar=findViewById(R.id.titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {

            @Override
            public void onLeftClick(View v) {
                BigBugFirstFeed.this.finish();
            }
            @Override
            public void onTitleClick(View v) { }
            @Override
            public void onRightClick(View v) { }
        });

        tv_big_out_date = findViewById(R.id.tv_big_out_date);
        tv_big_out_date.setText(simpleDateFormat.format(new Date()));
        tv_big_out_date.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDatePickerDialog(BigBugFirstFeed.this, 2, tv_big_out_date, calendar);
            }
        });

        formater.setMaximumFractionDigits(4);
        formater.setGroupingSize(0);
        formater.setRoundingMode(RoundingMode.FLOOR);

        tv_number = findViewById(R.id.tv_number);
        et_per_box_material = findViewById(R.id.et_per_box_material);

        batch_content = findViewById(R.id.batch_content);
        batch_content.setText(toAddBox.toString());
//        bigBoxId = findViewById(R.id.select_big_box_id);
//        start_date = findViewById(R.id.big_bug_breed_start_date);
//        box_number = findViewById(R.id.jialiao_count);
//        box_name = findViewById(R.id.box_name);
//        box_weight = findViewById(R.id.box_weight);
        //第一次加料重量
        jialiao_weight = findViewById(R.id.jialiao_weight);
        remark = findViewById(R.id.remark);

        bigBugBatchGroupNumberFirstAddList = new ArrayList<>();

        et_breed_no = findViewById(R.id.et_breed_no);
        et_middle_worm_quality = findViewById(R.id.et_middle_worm_quality);
//        et_middle_worm_quality.setListener();

        //自动生成：小虫虫及渣净重/中虫分盒数x中虫数量

        et_middle_worm_quality.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if(toAddBox.getBoxQuality() == null){
                    Toast.makeText(BigBugFirstFeed.this, "请检查数据库中虫分盒数异常", Toast.LENGTH_SHORT).show();
                    return;
                }
                if(et_middle_worm_quality.getText().toString().equals("")){
                    return;
                }
                Double etTarget =toAddBox.getPerBox() * Double.parseDouble(et_middle_worm_quality.getText().toString());
                et_target.setText(formater.format(etTarget));
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });



        et_target = findViewById(R.id.et_target);
        et_fact = findViewById(R.id.et_fact);

        sp_go_where = findViewById(R.id.sp_go_where);
        ArrayAdapter<String> goWhereAdapter = new ArrayAdapter<>(BigBugFirstFeed.this, android.R.layout.simple_spinner_item, gowhereList);
        sp_go_where.setAdapter(goWhereAdapter);
        sp_go_where.setSelection(0,true);

        tv_number.setText(serialId+"");


        System.out.println(toAddBox.getId() + "," + toAddBox.getTotalWeight() + ","  + toAddBox.getNetWeight() + ","
                + toAddBox.getBoxQuality() + ","  + toAddBox.getPerBox() + ","  + toAddBox.getPerBoxMaterial() );
    }

    /**
     * 称重接口
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String weight = data.getStringExtra("weight");
        switch (activeButton){
            case "btn_get_fact":
                et_fact.setText(weight);
                break;
            case "btn_get_per_weight":
                et_per_box_material.setText(weight);
                break;
        }
    }
    public void goWeight(View view) {
        switch (view.getId()) {
            case R.id.btn_get_fact:
                activeButton = "btn_get_fact";
                break;
            case R.id.btn_get_per_weight:
                activeButton = "btn_get_per_weight";
                break;
            default:
                break;
        }
        Intent intent = new Intent(BigBugFirstFeed.this, WeightActivity.class);
        startActivityForResult(intent, 1);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Intent intent = new Intent();
        intent.putExtra("needRefresh", true);
        setResult(RESULT_OK, intent);
    }

    @SuppressLint("SetTextI18n")
    public void save(View view) {
        if (sp_go_where.getSelectedItem().toString().equals("")) {
            Toast.makeText(this, "请选择大虫去向", Toast.LENGTH_SHORT).show();
            return;
        }
        if(et_breed_no.getText().toString().equals("")) {
            Toast.makeText(this, "请填写中虫培育盒号", Toast.LENGTH_SHORT).show();
            return;
        }
        if(et_middle_worm_quality.getText().toString().equals("")) {
            Toast.makeText(this, "请填写中虫数量", Toast.LENGTH_SHORT).show();
            return;
        }
        if(et_target.getText().toString().equals("")) {
            Toast.makeText(this, "请填写中虫虫、渣（目标值）", Toast.LENGTH_SHORT).show();
            return;
        }
        if(et_fact.getText().toString().equals("")) {
            Toast.makeText(this, "请获取中虫虫、渣（实际值）", Toast.LENGTH_SHORT).show();
            return;
        }
        if(et_per_box_material.getText().toString().equals("")) {
            Toast.makeText(this, "请获取中虫每盒加培育料", Toast.LENGTH_SHORT).show();
            return;
        }
        if(tv_big_out_date.getText().toString().equals("")) {
            Toast.makeText(this, "请选择大虫出料日期", Toast.LENGTH_SHORT).show();
            return;
        }


        new AlertDialog.Builder(this)
                .setTitle("确定保存吗？")
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) ->
                        Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show()))
                .setPositiveButton("确定", (dialog, which) -> {

                    //提交请求
                    RequestQueue queue = Volley.newRequestQueue(this);
                    String url = Config.url + "/hsmpy/middleWormBreedingFeed/add";
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");
                                        if (code.startsWith("2")){
                                            Toast.makeText(BigBugFirstFeed.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                                    et_breed_no.setText("");
                                                    et_fact.setText("");
                                                    et_middle_worm_quality.setText("");
                                                    et_target.setText("");
                                        }
                                        else{
                                            Toast.makeText(BigBugFirstFeed.this, "保存失败, 加料数量达到上限", Toast.LENGTH_SHORT).show();
                                            BigBugFirstFeed.this.finish();
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(BigBugFirstFeed.this, "保存失败, 加料次数达到上限", Toast.LENGTH_SHORT).show();
                            BigBugFirstFeed.this.finish();
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> map=new HashMap<>();
//                            Log.d("id",toAddBox.getId());
//                            Log.d("batch", toAddBox.getBatch());
//                            Log.d("worm_group", toAddBox.getGroup());
//                            Log.d("small_box_number", toAddBox.getSmallNum());
//                            Log.d("bigstart_time", toAddBox.getBeginDate());
//                            Log.d("sma_box_material_weight", toAddBox.getTotalWeight().toString());
//                            Log.d("sma_bug_material_weight", toAddBox.getNetWeight().toString());
//                            Log.d("number", toAddBox.getBoxQuality().toString());
//                            Log.d("per_bug_material_weight", toAddBox.getPerBox().toString());
//                            Log.d("big_bug_material_weight", et_per_box_material.getText().toString());
//                            Log.d("serial", tv_number.getText().toString());
//                            Log.d("go_where", sp_go_where.getSelectedItem().toString());
//                            Log.d("big_box_number", "PY"+et_breed_no.getText().toString());
//                            Log.d("big_bug_number", et_middle_worm_quality.getText().toString());
//                            Log.d("big_target_value", et_target.getText().toString());
//                            Log.d("big_get_value", et_fact.getText().toString());
//                            Log.d("big_bug_breed_end_time", tv_big_out_date.getText().toString());
                            map.put("id", toAddBox.getId());
                            map.put("batch", toAddBox.getBatch());
                            map.put("worm_group", toAddBox.getGroup());
                            map.put("small_bug_breed_box_number", toAddBox.getTinyNum());
                            map.put("big_bug_breed_start_time", toAddBox.getBeginDate());
                            map.put("small_bug_box_material_weight", toAddBox.getTotalWeight().toString());
                            map.put("small_bug_material_weight", toAddBox.getNetWeight().toString());
                            map.put("number", toAddBox.getBoxQuality().toString());
                            map.put("per_bug_material_weight", toAddBox.getPerBox().toString());
                            map.put("big_bug_per_box_breed_material_weight", et_per_box_material.getText().toString());
                            map.put("serial", tv_number.getText().toString());
                            map.put("go_where", sp_go_where.getSelectedItem().toString());
                            map.put("big_bug_breed_box_number", "PY"+et_breed_no.getText().toString());
                            map.put("big_bug_number", et_middle_worm_quality.getText().toString());
                            map.put("big_bug_material_target_value", et_target.getText().toString());
                            map.put("big_bug_material_get_value", et_fact.getText().toString());
                            map.put("big_bug_breed_end_time", tv_big_out_date.getText().toString());
                            map.put("factory",factory);

//                            toAddBox.getSerialId()+1

                            Log.d("before",serialId+"");
                            serialId++;
                            tv_number.setText(""+serialId);
                            Log.d("after",serialId+"");
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);

                })
                .show();
    }

    /**
     * 日期选择
     * @param activity
     * @param themeResId
     * @param tv
     * @param calendar
     */
    public static void showDatePickerDialog(Activity activity, int themeResId, final TextView tv, Calendar calendar) {
        // 直接创建一个DatePickerDialog对话框实例，并将它显示出来
        new DatePickerDialog(activity, themeResId, new DatePickerDialog.OnDateSetListener() {
            // 绑定监听器(How the parent is notified that the date is set.)
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                // 此处得到选择的时间，可以进行你想要的操作
                tv.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
            }
        }
                // 设置初始日期
                , calendar.get(Calendar.YEAR)
                , calendar.get(Calendar.MONTH)
                , calendar.get(Calendar.DAY_OF_MONTH)).show();
    }
}